package com.guli.gulimall.guliessearch.service.imp;

import com.alibaba.fastjson.JSON;
import com.guli.gulimall.guliessearch.constant.EsConstant;
import com.guli.gulimall.guliessearch.service.ProductSavaService;
import com.guli.to.es.SkuEsModel;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class ProductSavaServiceImp implements ProductSavaService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public Boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {
        //1给es中建立索引，PRODUCT_INDEX ，建立好映射关系
        //2给es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : esModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);

            indexRequest.source(JSON.toJSONString(esModel),XContentType.JSON);
            indexRequest.id(String.valueOf(esModel.getSkuId()));
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest,EsConstant.COMMON_OPTIONS);
        // TODO: 2022/5/12 如果批量保存失败
        boolean b = bulkItemResponses.hasFailures();
        List<String> collect = Arrays.stream(bulkItemResponses.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if (b){
         log.error("商品上架失败：{}",collect);
        }
        System.out.println(bulkItemResponses);
        return  b;
    }
}
